package com.tony.pmp.server.controller;

import com.google.common.collect.Maps;
import com.tony.pmp.common.response.BaseResponse;
import com.tony.pmp.common.response.StatusCode;
import com.tony.pmp.common.utils.AutoIncrementUtil;
import com.tony.pmp.common.utils.Constant;
import com.tony.pmp.model.entity.SysProductClassifyEntity;
import com.tony.pmp.server.annotation.LogAnnotation;
import com.tony.pmp.server.service.SysProductClassifyService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: SysProductClassifyController
 * @Auther: 皮蛋布丁
 * @Date: 2021/08/06/14:44
 * @Description: 商品类比
 */
@RestController
@RequestMapping("/sys/classify")
public class SysProductClassifyController extends AbstractController{

    @Autowired
    private SysProductClassifyService sysProductClassifyService;

    /**
    * @Description: list 获取商品类别列表
    * @Param: []
    * @return: java.util.List<com.tony.pmp.model.entity.SysProductClassifyEntity>
    * @Author: 皮蛋布丁
    * @Date: 2021/8/7 10:44
    */
    @RequestMapping("/list")
    @RequiresPermissions("sys:classify:list")
    public List<SysProductClassifyEntity> list() {
        return sysProductClassifyService.queryAll();
    }

    /**
    * @Description: select 获取树形商品类别列表数据
    * @Param: []
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/7 11:12
    */
    @RequestMapping("/select")
    public BaseResponse select() {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            List<SysProductClassifyEntity> list = sysProductClassifyService.queryAll();

            SysProductClassifyEntity root = new SysProductClassifyEntity();
            root.setId(Constant.TOP_CLASSIFY_ID);
            root.setClassifyValue(Constant.TOP_CLASSIFY_NAME);
            root.setParentClassifyId(-1);
            root.setOpen(true);
            list.add(root);

            resMap.put("classifyList",list);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    /**
    * @Description: save 新增商品分类
    * @Param: [entity]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/8 10:26
    */
    @RequestMapping(value = "/save",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresPermissions("sys:classify:save")
    public BaseResponse save(@RequestBody SysProductClassifyEntity entity) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("新增商品分类数据为：{}",entity);
            //验证商品分类参数是否正确
            String result = this.validateForm(entity);
            if (StringUtils.isNotBlank(result)) {
                return new BaseResponse(StatusCode.Fail.getCode(),result);
            }
            //二级分类
            if (entity.getParentClassifyId() != 0) {
                entity.setParentClassifyId(sysProductClassifyService.getById(entity.getParentClassifyId()).getId());
                log.info("重新赋值parentId的商品分类数据为：{}",entity);
            }
            entity.setCode(new AutoIncrementUtil().stringAuto(1,sysProductClassifyService.getMaxCodeByParentId(entity.getParentClassifyId())));
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setCreateUserId(Math.toIntExact(getUserId()));
            entity.setUpdateUserId(Math.toIntExact(getUserId()));
            log.info("新增商品分类的状体为：{}",sysProductClassifyService.save(entity));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: validateForm 验证商品分类参数是否正确
    * @Param: [entity]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/8/8 10:30
    */
    private String validateForm(SysProductClassifyEntity entity) {
        if (StringUtils.isBlank(entity.getClassifyValue())) {
            return "分类名称不能为空！";
        }
        //一级分类
        int firstClassifyType = Constant.ProductClassify.FIRST.getValue();
        //二级分类
        int secondClassifyType = Constant.ProductClassify.SECOND.getValue();
        if (entity.getClassifyLevel() == firstClassifyType && entity.getParentClassifyId() != 0) {
            return "父级类别必须为一级分类！";
        } else if (entity.getClassifyLevel() == secondClassifyType && entity.getParentClassifyId() == 0) {
            return "父级类别必须为二级分类";
        }
        return "";
    }

    /**
    * @Description: info 根据id获取商品分类信息
    * @Param: [id]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/8 19:35
    */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:classify:info")
    public BaseResponse info(@PathVariable int id) {
        if (id <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            resMap.put("classify",sysProductClassifyService.getClassifyById(id));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    /**
    * @Description: update 根据id修改商品分类信息
    * @Param: [entity]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/8 20:21
    */
    @LogAnnotation("修改商品分类")
    @RequestMapping(value = "/update",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresPermissions("sys:classify:update")
    public BaseResponse update(@RequestBody SysProductClassifyEntity entity) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("修改商品分类的数据为：{}",entity);
            String result = this.validateForm(entity);
            if (StringUtils.isNotBlank(result)) {
                return new BaseResponse(StatusCode.Fail.getCode(),result);
            }
            int parentId = sysProductClassifyService.getClassifyById(entity.getId()).getParentClassifyId();
            if (parentId != entity.getParentClassifyId()) {
                entity.setParentClassifyId(parentId);
            }
            entity.setUpdateUserId(Math.toIntExact(getUserId()));
            entity.setUpdateTime(new Date());
            log.info("修改商品分类的状态为：{}",sysProductClassifyService.updateById(entity));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: delete 根据id删除商品分类
    * @Param: [id]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/8 20:54
    */
    @LogAnnotation("删除商品分类信息")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @RequiresPermissions("sys:classify:delete")
    public BaseResponse delete(int id) {
        if (id <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("删除商品分类的id为：{}",id);
            SysProductClassifyEntity entity = sysProductClassifyService.getClassifyById(id);
            if (entity == null) {
                return new BaseResponse(StatusCode.InvalidParams);
            }
            if (entity.getParentClassifyId() == 0) {
                if (sysProductClassifyService.getClassifyByParentId(entity.getId())) {
                    return new BaseResponse(StatusCode.Fail.getCode(),"该分类下存在子分类！");
                }
            }
            sysProductClassifyService.delete(id);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
}
